package com.browsesoft.baseadapter;

import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Element;

import com.browsesoft.Entity;
import com.browsesoft.EntityManager;

/**
 * 该类实体可以处理延迟加载情形
 */
public class HTMLLazyEntityModel extends AdvancedSimpleEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8847140322667581537L;

	/**
	 * 带数据时要被替换的元素
	 */
	private String body;

	/**
	 * 页面元素
	 */
	protected Element e = null;

	/**
	 * 空构造
	 */

	public HTMLLazyEntityModel() {
		super();
	}

	/**
	 * 带属性构造
	 */
	public HTMLLazyEntityModel(Hashtable ht) {
		super(ht);
	}

	/**
	 * 初始化页面
	 * 
	 * @param request
	 *            请求
	 * @throws Exception
	 */
	public void init(HttpServletRequest request) throws Exception {
		super.init(request);
		// 取得页面元素
		e = this.getComponent().getPage().getElement();
		this.body = this.getComponent().getElement().getAttribute("onload");
	}

	/**
	 * 处理请求
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		super.service(request, response);
		// 得到光标指定的文本筐值
		String tabindex = (String) request.getParameter("tabindex");
		if (tabindex == null || tabindex.equals("")) {
			tabindex = "1";
		}
		// 换body中#first#
		String body = this.body.replaceAll("#first#", tabindex);
		this.getComponent().getPage().addOnload(body);
	}

	/**
	 * 取实体，以延迟方式取
	 * 
	 * @param name
	 *            参数名
	 * @param param
	 *            参数值
	 * @return 实体列表
	 */
	protected Entity getEntity(HttpServletRequest request, String name,
			String param) {
		try {
			// 得到实体类型
			String entityType = request.getParameter(name + "_entitytype");
			return EntityManager.getInstance().getObject(entityType, param,
					this.BasicComponent.getPage());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}